import json
import socket
import struct
import asyncio
import threading


# def handle_client(host,port,client_socket):
#     print(f"")
#     socket_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#     socket_client.connect((host,port))
#     try:
#         if
#         socket_client.listen(f"用户已链接")


#
# oringal_json = {
#     "jack": 18,
#     "jesscia": "29",
#     "tom": 18
# }
# print
#
# str = 123
#
# num = int(12185)
#
#
# def conv_hex_data(json: str, byte_length: int) -> int:
#     conv_json = int(json)
#
#     try:
#         if byte_length not in (1, 2):
#             raise ValueError
#         byte_data = conv_json.to_bytes(byte_length, byteorder='big', signed=False)
#         return int.from_bytes(byte_data, byteorder='big', signed=False)
#
#     except:
#         print("转换失败")
#
#     # oringal_json =
#     # str = num.to_bytes()
#
#
# # def sent_data(self):
# #     host = '192.168.1.103'
# #     port = 5001
# #
# #     try:
# #         tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 1)
# #         tcp_client.bind()
# #
# #         while True:
# #             print(f"正在发送数据")
# #             tcp_client.sendto("")
#
# def conv_data_to_byte(data,byte_length):
#     if data not in (1,2):
#         if data == str:
#


# def sent_data(data: str, target_addr: tuple) -> None:
#     # 实例化socket对象,STREAM是TCP参数
#     socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#     # 通过connect方法，传入元组，包含IP和端口，建立连接
#     socket_client.connect(target_addr)
#     try:
#         while True:
#
#             if not data:
#                 # 如果数据为空则跳出
#                 break
#                 # 发送数据包
#
#             socket_client.sendall((data + "##END##").encode('utf-8'))  # encode('utf-8')
#
#             # socket_client.shutdown(socket.SHUT_WR)  # 优雅关闭写入通道
#             response = socket_client.recv(1024)  # 可选：等待服务器确认
#             if not response:
#                 # 如果没收到回复，跳出循环重新执行
#                 break
#             print(f"服务器次数为{response.decode().count('h')}")
#             print(f"服务器握手信息为：{response.decode()}")
#     except KeyboardInterrupt as e:
#         print(f"服务端手动停止，错误信息为{e}")
#     except ConnectionError as e:
#         print(f"客户端断开连接，错误信息为：{e}")
#     except KeyError as e:
#         print(f"远程客户端发送数据错误，{e}")
#     except OSError as e:
#         print(f"触发系统连接错误，错误信息为：{e}")
#     finally:
#         socket_client.close()
def sent_data(data: str, target_addr: tuple) -> None:
    socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket_client.connect(target_addr)

    try:
        # 发送数据（添加结束标识符）
        socket_client.sendall((data + "##END##").encode()).  # 添加消息边界[1](@ref)
        socket_client.send().to_bytes()
        # 接收数据（循环直到完整接收）
        response = b""
        while True:
            chunk = socket_client.recv(1024)
            if not chunk:  # 连接关闭
                break
            response += chunk
            if b"##END##" in response:  # 检测结束标记
                response = response.replace(b"##END##", b"")
                break

        # 数据处理与打印
        if response:
            decoded = response.decode('utf-8')
            print(f"服务器响应长度：{len(decoded)}字符")
            print(f"字符'5'出现次数：{decoded.count('5')}")  # 修正统计方法
            print(f"完整响应内容：\n{decoded}")
        else:
            print("未接收到有效数据")

    except ConnectionResetError:
        print("连接被服务器重置[7](@ref)")
    except socket.timeout:
        print("接收超时[4](@ref)")
    finally:
        socket_client.close()  # 最终关闭连接


if __name__ == '__main__':
    sent_data("helloworld", ('192.168.1.107', 5003))
